package com.ifd.gui;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class JTextFieldLimit extends PlainDocument {
	private int limit;
	// optional uppercase conversion
	private boolean toUppercase = false;

	private boolean isNumericOnly = false;
	public JTextFieldLimit(int limit) {
		super();
		this.limit = limit;
	}

	public JTextFieldLimit(int limit, boolean upper) {
		super();
		this.limit = limit;
		toUppercase=upper;
	}

	public JTextFieldLimit(int limit, boolean upper, boolean numericOnly) {
		super();
		this.limit = limit;
		toUppercase=upper;
		setNumericOnly(numericOnly);
	}


	
	public void setNumericOnly(boolean numericOnly){
		isNumericOnly=numericOnly;
	}
	public void insertString(int offset, String str, AttributeSet attr)
			throws BadLocationException {
		boolean insert=true;
		if (str == null)
			return;
				
		if ((getLength() + str.length()) <= limit) {
			if(isNumericOnly && (str.compareTo("0")<0 || str.compareToIgnoreCase("9")>0))
					insert=false;
			if (toUppercase)
				str = str.toUpperCase();
			if(insert)
				super.insertString(offset, str, attr);
		}
	}
}